/**
 * Copyright(c)2013 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.custom;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

/**
 * @description java.sql.Timestamp类型日期转换器
 * 说明：因为java.sql.Timestamp继承了java.util.Date，所以该转换器通用于java.util.Date
 * @author aokunsang
 * @date 2013-6-21
 */
public class CustomTimestampConverter implements Converter<String, Timestamp> {

	private String timestampFormatPattern;  //转换的格式
	
	public CustomTimestampConverter(String timestampFormatPattern){
		this.timestampFormatPattern = timestampFormatPattern;
	}
	
	@Override
	public Timestamp convert(String source) {
		SimpleDateFormat sdf = new SimpleDateFormat(timestampFormatPattern);
		if(!StringUtils.hasLength(source)) {
            return null;
		}
		Date date = null;
		try {
			date = sdf.parse(source);
			return new Timestamp(date.getTime());
		} catch (ParseException e) {
			throw new IllegalArgumentException(String.format("类型转换失败，需要格式%s，但格式是[%s]", timestampFormatPattern, source));
		}
	}
}
